<template>
  <div>
    <canvas id="my-canvas"></canvas>
    <div class="contaner">
      <div id="color"></div>
      <div id="text"></div>
    </div>
    <button class="btn">灰度</button>
    <br>
    <div class="input-wrap">
      <input type="text" name="" id="txt" placeholder="输入发射文字...">
      <button id="btn" class="btn1">发射</button>
    </div>
    <canvas id="canvas" width="300" height="300"></canvas>
  </div>
</template>

<script>
import { defineComponent, onMounted } from 'vue';

export default defineComponent({
  setup () {
    function imageBase64 (url, callback, outputFormat) {
      let canvas = document.createElement('canvas'),
        ctx = canvas.getContext('2d'),
        img = new Image();
      img.crossOrigin = 'Anonymous';
      img.onerror = () => {
        console.log('图片加载失败')
      }
      img.onload = () => {
        canvas.height = img.height;
        canvas.width = img.width;
        ctx.drawImage(img, 0, 0);
        let dataUrl = canvas.toDataURL(outputFormat || 'image/png');
        callback && callback.call(this, dataUrl);
        canvas = null;
      }
      img.src = url;
    }
    imageBase64(require('../../assets/img/bg.jpeg'), (base64) => {
      let img = new Image();
      img.src = base64;
      img.crossOrigin = '';
      let canvas = document.getElementById('my-canvas'),
        color = document.getElementById('color'),
        text = document.getElementById('text');
      canvas.width = 200;
      canvas.height = 200;
      let ctx = canvas.getContext('2d');
      img.onload = function () {
        ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
        draw.call(this, {ctx, canvas })
      }
      function pick(event) {
        // 获取鼠标坐标
        let x = event.layerX;
        let y = event.layerY;
        // 获取图片像素信息
        let pixel = ctx.getImageData(x, y, 1, 1).data;
        let rgba = `rgba(${pixel[0]},${pixel[1]},${pixel[2]},${pixel[3]/255})`;
        color.style.backgroundColor = rgba;
        text.textContent = rgba;
      }
      canvas.addEventListener('mousemove', pick);
    })

    function draw({ctx, canvas}) {
      let imgData = ctx.getImageData(0, 0, canvas.width, canvas.height)
      let data = imgData.data;
      // 求出每个像素的灰色，然后把改变后的像素信息重新添加到canvas中
      let grayscale = () => {
        for (let i=0; i< data.length; i+=4) {
          let avg = (data[i]+ data[i+1]+ data[i+2]) / 3;
          data[i] = avg; //red
          data[i+1] = avg; //green
          data[i+2] = avg; //blue
        }
        ctx.putImageData(imgData, 0, 0)
      }
      let btn = document.querySelector('.btn');
      btn.addEventListener('click', grayscale);
    }
    onMounted(() => {
      let canvas = document.getElementById("canvas"),
        ctx = canvas.getContext('2d'),
        winWidth = 300,
        winHeight = 300;

      canvas.width = winWidth;
      canvas.height = winHeight;
      ctx.textBaseline = 'top';

      let fontSize = 500,
        fontFamily = 'Helvetica Neue, Helvetica, Arial, sans-serif';
      document.querySelector("#btn").addEventListener("click", function () {
        init();
      })

      let dotList = [];
      var rafId = null;
      function init () {
        let s = 0,
          input = document.querySelector('#txt'),
          l = input.value ? input.value : 'Beta';
        input.value = '';
        if (rafId) cancelAnimationFrame(rafId);
        setFontSize(fontSize)
        s = Math.min(fontSize,
          (canvas.width / ctx.measureText(l).width) * 0.8 * fontSize,
          (canvas.height / fontSize) * (isNumber(l) ? 1 : 0.5) * fontSize);
        setFontSize(s);
        
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.fillText(l, 10, 0)
        ctx.fillStyle = '#f00'
        dotList = [];
        handleCanvas();
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        draw2();

        console.log(fontFamily, dotList, rafId, s)
      }
      function setFontSize(s) {
        ctx.font = s + 'px ' + fontFamily;
      }
      function isNumber(n) {
        return !isNaN(parseFloat(n)) && isFinite(n);
      }
      function handleCanvas() {
        let imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
        console.log(imgData)
        for (let x=0; x<imgData.width; x+=6) {
          for (let y=0; y<imgData.height; y+=6) {
            let i = (y*imgData.width + x) * 4;
            if (imgData.data[i+3] > 128 && imgData.data[i] < 100) {
              dotList.push(new Dot(x, y, 2))
            }
          }
        }
      }
      function Dot(centerX, centerY, radius) {
        this.x = centerX;
        this.y = centerY;
        this.radius = radius;
        this.frameNum = 0;
        this.frameCount = Math.ceil(3000 / 16.66);
        this.sx = 400;
        this.sy = 400;
        this.delay = this.frameCount * Math.random();
        this.delayCount = 0;
      }
      // t 当前时间
      // b 初始值
      // c 总位移
      // d 总时间
      function easeInOutCubic(t, b, c, d) {
        if ((t /= d / 2) < 1) return c / 2 * t * t * t + b;
        return c / 2 * ((t -= 2) * t * t + 2) + b;
      }
      function draw2() {
        ctx.clearRect(0, 0, winWidth, winHeight);
        ctx.fillStyle = "#000";
        var len = dotList.length,
          curDot = null,
          frameNum = 0,
          frameCount = 0,
          curX, curY,
          finishCount = 0;
        for (var i = 0; i < len; i += 1) {
          // 当前粒子
          curDot = dotList[i];

          // 获取当前的time和持续时间和延时
          frameNum = curDot.frameNum;
          frameCount = curDot.frameCount;

          if (curDot.delayCount < curDot.delay) {
            curDot.delayCount += 1;
            continue;
          }
          ctx.save();
          ctx.beginPath();
          if (frameNum < frameCount) {
            curX = easeInOutCubic(frameNum, curDot.sx, curDot.x - curDot.sx, curDot.frameCount);
            curY = easeInOutCubic(frameNum, curDot.sy, curDot.y - curDot.sy, curDot.frameCount);

            ctx.arc(curX, curY, curDot.radius, 0, 2 * Math.PI);
            curDot.frameNum += 1;

          } else {
            ctx.arc(curDot.x, curDot.y, curDot.radius, 0, 2 * Math.PI);
            finishCount += 1;
          }
          ctx.fill();
          ctx.restore();
          if (finishCount >= len) {
            cancelAnimationFrame(rafId);
            return;
          }
        }
        rafId = requestAnimationFrame(draw2);
      }
    })
  }
})
</script>

<style lang="scss" scoped>
body{
  background-color: #f2f2f2;
}
canvas{
  display: block;
}
input{
  width: 200px;
  height: 30px;
  border: 1px solid #e0e0e0;
  background: 0 0;
  -webkit-appearance: none;
  outline: 0;
  margin-right: 10px;
  padding-left: 5px;
  box-sizing: border-box;
}
.btn1 {
    height: 30px;
    line-height: 30px;
    padding: 0 11px;
    cursor: pointer;
    min-width: 55px;
    display: inline-block;
    position: relative;
    text-align: center;
    font-size: 15px;
    vertical-align: top;
    -webkit-box-sizing: border-box;
    border: 1px solid #0baae4;
    border-radius: 3px;

    background-color: #18b4ed;
    background-image: -webkit-gradient(linear,left top,left bottom,color-stop(0.5,#1fbaf3),to(#18b4ed));
    color: #fff;
    -webkit-background-clip: padding-box;
    background-clip: padding-box;
    -webkit-appearance: none;
    outline: none;
}

.btn1:active {
  background: #1ca7da;
  border-color: #1ca7da;
  color: rgba(255,255,255,.5);
}
.input-wrap{
  margin: 20px;
}
.contaner{
  display: flex;
  height: 40px;
  width: 300px;
}
#color{
  width: 40px;
  height: 40px;
}
#text{
  padding-left: 10px;
  line-height: 40px;
}
.btn{
  display: block;
  background-color: #ff0081;
  color: #fff;
  border-radius: 4px;
  border: none;
  cursor: pointer;
  outline: none;
  padding: 10px 20px;
  box-shadow: 0 2px 25px rgba(255, 0, 130, 0.5);
}
</style>

